<template>
  <div v-if="isPrintPF" style="width:100%">
    <el-button @click="openDialog()" type="primary" :disabled="!mixEditable">{{ buttonText || '打印办理单'}}</el-button>
    <pm-dialog
        title="打印办理单"
        :visible.sync="dialogVisiable"
        width="700"
        :close-on-click-modal="false"
        :showFullScreenButton="true"
        append-to-body
        :before-close="handleClose"
      >
        <div style="text-align: center;padding: 20px;">
          <div class="select-image-container" :style="layoutStyle">
        <div
          v-for="(dataImage, index) in imageLists"
          :key="index"
          style="margin: 10px 30px 0 0;"
        >
          <div @click="onSelectMultipleImage(dataImage)" style="background-color: #f5f7fa;padding-top: 10px;">
            <img
              :src="getImageSrc(dataImage)"
              :id="dataImage.id"
              style="height: 80px;width: 120px;"
              class="select-image__img"
            />
            <h4 :style="isExistInArray(dataImage.id) ? 'background: #a7b6f5' : ''">{{ dataImage.name }}</h4>
            <!-- <div class="alt-text">{{ dataImage.alt }}</div> -->
          </div>
        </div>
      </div>
          <!-- <el-button type="primary" @click="previewOfd">预览</el-button>
          <el-button type="primary">
            <a :href="downloadUrl" >下载</a>
          </el-button> -->
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="cancel">取消</el-button>
          <el-button size="mini" type="primary" @click="handlerProcessingForm">确定</el-button>
        </span>
    </pm-dialog>
  </div>
  <div v-else style="width:100%; display:flex;">
    <el-button @click="handlerProcessingForm" type="primary" :disabled="!mixEditable">{{ buttonText || '编辑查看'}}</el-button>
    <el-radio-group v-model="currentTemp" style="margin-top:3px;">
      <el-radio v-for="(dataImage, index) in imageLists" :label="dataImage" :key="index">{{ dataImage.name }}</el-radio>
    </el-radio-group>
  </div>
</template>
<script>
import { isString, isEmpty } from 'lodash'
import { loadRoute3Path } from '@/utils/loadRemote'
import routerContextPath from '../../mixins/router-context-path.js'
const mfpConfig = require('../../../build/mfp.config.js')
import { installWpsAddin, _WpsInvoke } from 'base/utils'
export default {
  name: 'evaluationIndex',
  mixins: [routerContextPath],
  props: {
    // field
    value: '',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    template_url: '',
    template_filename: '',
    sample_list: null,
    fileName: {
      type: String,
      default: 'demo.docx'
    },
    extConfig: {
      type: Object,
      default: () => {}
    },
    images: {
      type: Array,
      default: () => [],
    },
    direction: {
      type: String,
      default: "horizontal",
    },
    format: {
      type: String,
      default: 'printPF'
    },
    buttonText: {
      type: String,
      default: ''
    }
  },
  computed: {
    isPrintPF() {
      return this.format !== 'RedHat'
    },
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
    fileSuffix() {
      return this.template_filename && this.template_filename.slice(this.template_filename.lastIndexOf('.') + 1)
    },
    fileType() {
      return this.options && this.fileSuffix && (this.options.find(o => o.types.includes(this.fileSuffix)) || {}).value || 'f'
    },
    imageLists() {
      return this.isDesigner
        ? this.dataImages
        : this.images;
    },
    isHorizontal() {
      return this.direction === "horizontal";
    },
    layoutStyle() {
      if (!this.isHorizontal) return { flexDirection: "column" };
    },
    userInfo() {
      return JSON.parse(localStorage.getItem('user'))
    },
    Authorization() {
      return this.userInfo.uniqueId
    },
    isLocalLoad() {
      // return true
      return (this.userInfo.attributes && this.userInfo.attributes.Extra || '1') === '1'
    }
  },
  data() {
    return {
      options: [{
        label: '文字文件 (word)',
        value: 'w',
        types: ['doc' , 'dot' , 'wps' , 'wpt' , 'docx' , 'dotx' , 'docm' , 'dotm']
      }, {
        label: '表格文件 (excel)',
        value: 's',
        types: ['xls' , 'xlt' , 'et' , 'xlsx' , 'xltx' , 'xlsm' , 'xltm']
      }, {
        label: '演示文件 (ppt)',
        value: 'p',
        types: ['ppt' , 'pptx' , 'pptm' , 'ppsx' , 'ppsm' , 'pps' , 'potx' , 'potm' , 'dpt' , 'dps']
      }, {
        label: 'PDF文件',
        value: 'f',
        type: ['pdf']
      }],
      dialogVisiable: false,
      downloadUrl: '',
      ofdId: '',
      dataImages: [
        {
          id: "1",
          name: "标题1",
        },
        {
          id: "2",
          name: "标题2",
        },
      ],
      selectedImages: [], // 已选择数据
      multipleSelected: [],
      currentTemp: null
    }
  },
  created(){
  },
  watch: {
   
  },
  methods: {
    openInsertRedHeader() {
      installWpsAddin()
      const { prefix, fileId, name } = this.formatData()
      let sampleUrl = ''
      let sampleName = ''
      let redFileElement = {}
      for (let i of this.sample_list) {
        if (i.type === 'DOCUMENT') {
          sampleUrl = i.sampleUrl
          sampleName = i.bookmark
        } else if (i.type === 'TEXT') {
          this.$set(redFileElement, i.bookmark, i.text)
        }
      }
      console.log(sampleUrl,sampleName,name,'====sampleUrl,sampleName,name')
      if (!fileId) return this.$message.warning('模板数据缺少fileId')
      const uploadPath = `${origin}/XFfileServer/fileSaveOrUpdate?userName=${this.userInfo.userName}`
      if (this.isPrintPF) {
        _WpsInvoke([{
            "OnlineEditDoc": {
              "uploadPath": uploadPath, // 保存文档上传接口
                "newFileName": name,
                SourcePath: name,
                "Authorization": this.Authorization,
                "userName": this.userInfo.userName,
                redFileElement, //书签
                "fileName": sampleUrl, // 文件书签
                "insertFileUrl": 'http://121.36.242.165:28090' + '/XFfileServer/fileDownload?id=' + fileId,
                "bkInsertFile": sampleName || 'strContent', //红头模板中填充正文的位置书签名
                "buttonGroups": "btnSaveAsFile,btnImportDoc,btnPageSetup,btnInsertDate,btnSelectBookmark" //屏蔽功能按钮
            }
        }],true,
            "http://127.0.0.1:8000/iestart/jsplugins.xml",
            false,
            (data) => {
              console.log(data,'===data')
              this.$emit('input', JSON.parse(data)[0].id)
              this.$emit('actionOver', JSON.parse(data)[0].id)
            })
      } else {
        _WpsInvoke([{
            "OnlineEditDoc": {
              "uploadPath": uploadPath, // 保存文档上传接口
                "newFileName": name,
                SourcePath: name,
                "Authorization": this.Authorization,
                "userName": this.userInfo.userName,
                redFileElement, //书签
                "suffix": 'doc',
                "fileName": sampleUrl, // 文件书签
                // "fileName": 'http://121.36.242.165:28090' + '/XFfileServer/fileDownload?id=' + fileId, // 文件书签
                "insertFileUrl": 'http://121.36.242.165:28090' + '/XFfileServer/fileDownload?id=' + fileId,
                "bkInsertFile": sampleName || 'strContent', //红头模板中填充正文的位置书签名
                "buttonGroups": "btnSaveAsFile,btnImportDoc,btnPageSetup,btnInsertDate,btnSelectBookmark" //屏蔽功能按钮
            }
        }],true,
            "http://127.0.0.1:8000/iestart/jsplugins.xml",
            false,
            (data) => {
              console.log(data,'===data')
              this.$emit('input', JSON.parse(data)[0].id)
              this.$emit('actionOver', JSON.parse(data)[0].id)
            })
      }
      
    },
    cancel(){
      this.dialogVisiable = false
      this.multipleSelected = []
    },
    getImageSrc(image) {
      const { id } = image
      const { name } = mfpConfig
      const url = loadRoute3Path('')
      const selectedStatus = this.isExistInArray(id) ? 'selected' : 'unselected'
      return `${url}/api/afc/components/${name}/static/${selectedStatus}.png`
    },
    openDialog() {
      this.dialogVisiable= true
      this.$emit('getSampleList')
    },
    formatData() {
      if (this.isPrintPF && !this.multipleSelected.length || !this.isPrintPF && !(this.currentTemp && this.currentTemp.id)) {
        this.$message.warning('请选择数据！')
        return false
      } else if (!this.sample_list.length) {
        this.$message.warning('请加载标签数据！')
        return false
      }
      const prefix = window.location.origin
      const {fileId, name} = this.multipleSelected[0] || this.currentTemp
      return {
        prefix, fileId, name
      }
    },
    async handlerProcessingForm() {
      if (this.isLocalLoad) {
        this.openInsertRedHeader()
        return
      }
      const { prefix, fileId, name } = this.formatData()
      const url = loadRoute3Path('')
      if (!fileId) return
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.wrapHeader, [{
        taskId: String(Math.random()*100000000).slice(0,7),
        templateFilename: name,
        sampleList: isString(this.sample_list) ? eval(this.sample_list) : this.sample_list,
        // sampleList: [{bookmark: "AffixName",type: "TEXT",text: "电影"},{bookmark: "AffixNames",type: "TEXT",text: "文艺片"}],
        templateUrl: prefix + url + '/XFfileServer/fileDownload?id=' + fileId,
        // http://121.36.242.165:28084/XFfileServer/fileDownload?id=517
      }])
      const { msg, data, code } = resp.data
      if (code === 200) {
        await this.downloadFormat(data, this.formatData())
      } else {
        this.$message.error(msg)
      }
    },
    async downloadFormat(info, item) {
      const target = item.name.slice(item.name.lastIndexOf('.') + 1)
      const { downloadId, routerKey } = info
      const user = localStorage.getItem('user')
      const data = {
        downloadId,
        routeKey: routerKey,
        userName: JSON.parse(user).userName,
        target,
        fileName: this.fileName,
        wThirdParams: JSON.parse(user).userName
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.operateDocumentResultDownload, data)
      if (!resp.error) {
        const {fileId}  = resp.data
        this.$emit('input', fileId)
        this.$emit('actionOver', fileId)
        this.editApp(resp.data)
        // this.downloadUrl = resp.data.downloadUrl
        // this.ofdId = resp.data.fileId
        // this.openAction()
      }
    },
    async editApp(item) {
      const user = localStorage.getItem('user')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkEdit, {
        fileId: item.fileId,
        type: item.type || 'w',
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=edit`)
      } else {
        this.$message.error(msg)
      }
    },
    openAction() {
      this.dialogVisiable = true
    },
    previewOfd() {
      this.previewApp({
        id: this.ofdId,
        type: this.fileType
      })
    },
    handleClose() {
      this.dialogVisiable = false
    },
    async previewApp(item) {
      const user = localStorage.getItem('user')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkView, {
        fileId: item.id,
        type: item.type || 'w',
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        // this.setToken(data.link)
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=preview`)
        // window.open(data.link)
      } else {
        this.$message.error(msg)
      }
    },
    classThumbnailMultiple(id, isDisabled) {
      const rootClass = "select-image";
      const baseClass = `${rootClass}__thumbnail`;
      const baseMultipleClass = `${baseClass} is--multiple`;
      if (isDisabled) {
        return `${baseMultipleClass} ${baseClass}--disabled`;
      }
      if (this.isExistInArray(id)) {
        return `${baseMultipleClass} ${baseClass}--selected`;
      }
      return `${baseMultipleClass}`;
    },
    isExistInArray(id) {
      return this.multipleSelected.find((item) => {
        return id === item.id;
      });
    },
    removeFromMultipleSelected(id) {
      this.multipleSelected = this.multipleSelected.filter((item) => {
        return id !== item.id;
      });
    },
    resetMultipleSelection() {
      this.multipleSelected = [];
    },
    onSelectMultipleImage(objectImage) {
      // console.log(objectImage,this.isExistInArray(objectImage.id),this.multipleSelected,'6666666666666666666');
      if (!objectImage.disabled) {
        this.$forceUpdate();
        this.$nextTick(() => {
          this.multipleSelected = [];
          if (!this.isExistInArray(objectImage.id)) {
            if (
              this.multipleSelected.length == 0 &&
              this.multipleSelected.length != 2
            ) {
              this.multipleSelected.push(objectImage);
              this.$emit("input", this.multipleSelected);
            } else {
              this.$message({
                message: "只能选择一条数据",
                type: "warning",
              });
            }
          } else {
            this.removeFromMultipleSelected(objectImage.id);
            this.$emit("input", this.multipleSelected);
          }
        });
      }
    },
    setInitialSelection() {
      if (this.selectedImages) {
          this.multipleSelected = [].concat(this.selectedImages);
      }
    },
  }
}
</script>
<style lang="scss" scoped>
  a {
  text-decoration: none;
  color: #fff;
}
a:hover {
  color: #fff;
}
.el-button.el-button--primary:hover {
  a {
    text-decoration: none;
    color: #fff;
  }
}
.select-image-container {
  display: flex;
}
.select-image__thumbnail {
  cursor: pointer;
  // width: 210px;
  // height: 182px;
  // padding:0px;
  // border: 1px solid #dddddd;
  border-radius: 4px;
  margin: 10px 30px 0 0;
}
.select-image__thumbnail--selected {
  background: #44c3ff;
  padding: 4px;
}

.select-image__thumbnail--disabled {
  background: #b9b9b9;
  cursor: not-allowed;
}

.select-image__thumbnail--disabled > .select-image__img {
  // opacity: 0.5;
 
}
.alt-text {
  font-size: 14px;
}
.footer-btn {
  display: flex;
  margin: 15px 0 0 20px;
}
h4 {
  background-color: #bfbfbf;
  margin: 0;
  margin-top: 10px;
  color: #fff;
  width: 200px;
  height: 40px;
  text-align: center;
  line-height: 40px;
}
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
.el-radio {
  margin-left: 15px;
}
button.el-button.el-button--primary.el-button--mini {
  height: 28px;
}
</style>